package com.iknowone.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.iknowone.entity.Params;
import com.iknowone.entity.Result;
import com.iknowone.entity.Status;

public abstract class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Result result = null;
		try {
			result = getResult(request);
		} catch (Exception e) {
			// LOGGER.error("..");
			result = new Result(null, new Status(
					HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
					"Internal error."));
		} finally {
			writeResultOnResponse(response, result);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse result)
			throws ServletException, IOException {
		doGet(request, result);
	}

	protected abstract Result getResult(HttpServletRequest request);

	private void writeResultOnResponse(HttpServletResponse response,
			Result result) throws IOException {
		response.setContentType("application/json");

		response.setStatus(HttpServletResponse.SC_OK);
		Gson gson = new Gson();
		response.setCharacterEncoding("UTF-8");
		String strResult = gson.toJson(result);
		response.getWriter().println(strResult);
		try {
			response.flushBuffer();
		} catch (IOException e) {
			// LOGGER.warn("Failed to flush buffer for response ", e);
		}
	}

	protected final Status checkMandatoryParameter(Params param,
			HttpServletRequest request) {
		Status status = new Status(HttpServletResponse.SC_OK, "Succes");
		String paramValue = request.getParameter(param.getValue());
		if (paramValue == null || paramValue.trim().equals("")) {
			status = new Status(HttpServletResponse.SC_BAD_REQUEST,
					"missing parameter");
		}
		return status;
	}
}